package com.example.test_witns.ui.register_finished;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.example.test_witns.R;
import com.example.test_witns.databinding.ActivityRegisterFinished1Binding;
import com.example.test_witns.utils.GlideEngine;
import com.example.test_witns.utils.OssUtil;
import com.example.test_witns.utils.Uuid_genHelper;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.engine.CropFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMUserFullInfo;
import com.yalantis.ucrop.UCrop;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

import de.hdodenhof.circleimageview.CircleImageView;

public class RegisterFinishedActivity1 extends Activity {
    ActivityRegisterFinished1Binding binding;
    String uuid_to_pass;
    String sig;
    String email;

    String endpoint = "oss-cn-beijing.aliyuncs.com";
    String accessKeyId = "LTAI5tMMT1mKsUbjgvunz56D";
    String accessKeySecret = "BxCzPRF4aTosxFnfrIZzAmLdatjoGV";
    String bucketName = "fftechuseravater";
    private String avatarURL;

    private CircleImageView register_set_avatar;
    String avatarURI;
    private static byte[] bytesFromImageUri;

    private ActivityResultLauncher<Intent> mGetContentLauncher;

    private static final int REQUEST_ALBUM = 1002;

    @Nullable
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        binding = ActivityRegisterFinished1Binding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        register_set_avatar = findViewById(R.id.register_set_avatar);

        View finished_1_complete = findViewById(R.id.finished_1_complete);

        TextView nickname = findViewById(R.id.nickname);
        View finished_1_skip = findViewById(R.id.finished_1_skip);
        Intent intent = getIntent();
        if(intent != null){
            sig = intent.getStringExtra("sig");
            email = intent.getStringExtra("email");
        }

        TextView finished_1_uuid_value = findViewById(R.id.finished_1_uuid_value);
        String uuid = Uuid_genHelper.gen_uuid();
        if (uuid != null) {
            finished_1_uuid_value.setText(uuid);
            uuid_to_pass = uuid;
        }



        finished_1_skip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), RegisterFinishedActivity2.class);
                //startActivity(intent);
            }
        });

        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
        OSS ossClient = new OSSClient(this, endpoint, credentialProvider);

        register_set_avatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 启动图片选择器，设置为单选模式
                PictureSelector.create(RegisterFinishedActivity1.this)
                        .openGallery(SelectMimeType.ofImage()) // 只打开图片选择
                        .setCropEngine(new CropFileEngine() {
                            @Override
                            public void onStartCrop(Fragment fragment, Uri srcUri, Uri destinationUri, ArrayList<String> dataSource, int requestCode) {
                                UCrop.Options options = new UCrop.Options();
                                options.setCircleDimmedLayer(true);
                                UCrop uCrop = UCrop.of(srcUri, destinationUri ,dataSource).withOptions(options);
                                uCrop.start(fragment.getActivity(), fragment, requestCode);
                            }
                        })
                        .setMaxSelectNum(1) // 设置最大选择图片数量为1
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                // 处理选择结果
                                if (!result.isEmpty()) {
                                    LocalMedia media = result.get(0);
                                    if (media != null){
                                        ContentResolver contentResolver = RegisterFinishedActivity1.this.getContentResolver();
                                        Uri imageUri = Uri.parse(media.getPath());
                                        if (imageUri != null) {
                                            // 处理获取到的图片URI
                                            // 例如，将其设置到ImageView或者进行其他处理
                                            register_set_avatar.setImageURI(imageUri);
                                            byte[] bytesFromImageUri = getBytesFromImageUri(RegisterFinishedActivity1.this, imageUri);
                                            if (register_set_avatar != null){
                                                Toast.makeText(RegisterFinishedActivity1.this, "更新成功", Toast.LENGTH_SHORT).show();
                                            }else {
                                                Toast.makeText(RegisterFinishedActivity1.this, "失败", Toast.LENGTH_SHORT).show();
                                            }
                                            avatarURI = imageUri.toString();
                                            avatarURL = email + UUID.randomUUID().toString() + ".jpg";

                                            uploadImageToOSS("fftechuseravater", "images/userIcon/" + avatarURL, null, imageUri);

                                        }
                                    }
                                    // 使用uri进行下一步操作，例如上传图片等
                                }
                            }

                            @Override
                            public void onCancel() {
                                // 处理取消事件
                            }
                        });
            }


        });

        finished_1_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!nickname.getText().toString().isEmpty()){
                    if (nickname.getText().toString().length() < 11){
                        if (bytesFromImageUri == null){
                            V2TIMUserFullInfo v2TIMUserFullInfo = new V2TIMUserFullInfo();
                            v2TIMUserFullInfo.setFaceUrl("https://fftechuseravater.oss-cn-beijing.aliyuncs.com/images/userIcon/15116785809%40163.com15caf9fb-961f-4f5f-a709-0303552d1743.jpg");
                            if(register_set_avatar.getDrawable() instanceof BitmapDrawable){
                                Bitmap bitmap1 = null;
                                bitmap1 = ((BitmapDrawable)register_set_avatar.getDrawable()).getBitmap();
                                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                                bitmap1.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                                bytesFromImageUri = outputStream.toByteArray();
                            }
                        }

                        HashMap<String, byte[]> uuidMap = new HashMap<>();
                        byte[] uuidBytes = uuid_to_pass.getBytes();
                        uuidMap.put("uuid", uuidBytes);

                        V2TIMUserFullInfo v2TIMUserFullInfo = new V2TIMUserFullInfo();
                        v2TIMUserFullInfo.setNickname(nickname.getText().toString());
                        v2TIMUserFullInfo.setCustomInfo(uuidMap);

                        V2TIMManager.getInstance().setSelfInfo(v2TIMUserFullInfo, new V2TIMCallback() {
                            @Override
                            public void onSuccess() {
//                                OssUtil.initOSS(getContext(), endpoint, accessKeyId, accessKeySecret, bucketName);
//                                uploadFile("fftechuseravater", "images/userIcon/" + email + UUID.randomUUID().toString(), avatarURI);
//                                Toast.makeText(getContext(), "设置成功", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onError(int i, String s) {
                                Toast.makeText(RegisterFinishedActivity1.this, "失败了,请检查网络或联系开发者", Toast.LENGTH_SHORT).show();
                            }
                        });
                        Intent intent = new Intent(getApplicationContext(), RegisterFinishedActivity2.class);
                        intent.putExtra("nickname", nickname.getText().toString());
                        intent.putExtra("uuid", uuid_to_pass);
                        intent.putExtra("sig",sig);
                        intent.putExtra("email", email);
                        intent.putExtra("avatar", bytesFromImageUri);
                        intent.putExtra("avatar_uri", avatarURI);
                        intent.putExtra("avatar_url", avatarURL);
                        startActivity(intent);
                    }else {
                        Toast.makeText(RegisterFinishedActivity1.this, "昵称不要超过10个字符哟", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(RegisterFinishedActivity1.this, "请设置一个昵称", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void launchGetContent() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true); // 限制为本地文件
        mGetContentLauncher.launch(intent);
    }

    public String getRealPathFromURI(Context context, Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
        cursor.close();
        return path;
    }

    public byte[] getBytesFromImageUri(Context context, Uri imageUri) {
        String path = getRealPathFromURI(context, imageUri);
        byte[] byteArray = null;
        try {
            FileInputStream fileInputStreamReader = new FileInputStream(path);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int n;
            while ((n = fileInputStreamReader.read(buffer)) != -1) {
                output.write(buffer, 0, n);
            }
            fileInputStreamReader.close();
            byteArray = output.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArray;
    }

    public void uploadFile(String bucketName, String objectKey, String filePath) {
        PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, filePath);
        OSSAsyncTask task = OssUtil.getOSSClient().asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("OSS", "上传成功");
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                if (clientExcepion != null) {
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    Log.e("OSS", "ServiceException: " + serviceException.getErrorCode());
                }
            }
        });
    }

    public void uploadImageToOSS(String bucketName, String objectName, byte[] imageBytes, Uri uri) {
        OSS ossClient = OssUtil.initOSS(RegisterFinishedActivity1.this, endpoint, accessKeyId, accessKeySecret, bucketName);
        try {
            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, uri);

            // 上传文件
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            // 打印结果
            if (result != null) {
                // 上传成功
                V2TIMUserFullInfo v2TIMUserFullInfo = new V2TIMUserFullInfo();
                v2TIMUserFullInfo.setFaceUrl("https://fftechuseravater.oss-cn-beijing.aliyuncs.com/images/userIcon/" + avatarURL);
                V2TIMManager.getInstance().setSelfInfo(v2TIMUserFullInfo, new V2TIMCallback() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(RegisterFinishedActivity1.this, "头像同步成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(int i, String s) {

                    }
                });
                Toast.makeText(RegisterFinishedActivity1.this, "上传成功", Toast.LENGTH_SHORT).show();
                System.out.println("Upload Success: " + result.getRequestId());
            } else {
                // 上传失败
                System.out.println("Upload Failed.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }
}
